package com.seek.inter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.seek.common.handler.SpringContextHolder;
import com.seek.model.dto.ResultInfo;
import com.seek.service.LoanService;
import com.seek.service.ReadService;
import com.seek.util.CommonUtil;

/**
 * 货款订单催收相关接口
 *
 */
public class LoanOverdueInter {
	private static Logger logger = LoggerFactory.getLogger(LoanOverdueInter.class);
	private LoanService loanService = (LoanService)SpringContextHolder.getBean("loanService");
	private ReadService readService = (ReadService)SpringContextHolder.getBean("readService");
	
	/**
	 * 获取待催收分配列表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getOverdueLoanList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		String custPhone = reqJson.getString("custPhone");
		String rqq = reqJson.getString("rqq");
		String rqz = reqJson.getString("rqz");
		int delayDays = CommonUtil.getIntValue(reqJson.getLong("delayDays"));
		int overdueSpan = CommonUtil.getIntValue(reqJson.getInteger("overdueSpan"));	
		int excludeBad = CommonUtil.getIntValue(reqJson.getLong("excludeBad"));
		String overduerId = reqJson.getString("overduerId");
		
		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		if (!CommonUtil.isEmpty(custPhone)){
			custPhone = "%"+custPhone+"%";
			where.append(" and b.phone_no like ?");
			params.add(custPhone);
		}
		if (!CommonUtil.isEmpty(rqq)){
			where.append(" and a.end_time > ?");
			params.add(rqq);
		}
		if (!CommonUtil.isEmpty(rqz)){
			rqz = rqz.substring(0,10)+" 23:59:59";
			where.append(" and a.end_time <= ?");
			params.add(rqz);
		}
		if (delayDays > 0){
			where.append(" and datediff(now(),a.end_time)>= ?");
			params.add(delayDays);
		}
		if (overdueSpan > 0){
			where.append(" and datediff(now(),ifnull(a.last_overdue_time,a.end_time))>= ?");
			params.add(delayDays);
		}
		if (excludeBad > 0){
			where.append(" and a.loan_status=3");
		}
		if(!StringUtils.isEmpty(overduerId)){
			if (CommonUtil.getIntValue(overduerId) == 0){
				where.append(" and a.overduer_id is null");
			}else if (CommonUtil.getIntValue(overduerId) > 0){
				where.append(" and a.overduer_id=?");
				params.add(CommonUtil.getIntValue(overduerId));
			}
		}
		
		// 取得总记录行数
		String sql = "select count(1) cnt from t_loan a, t_customer b where a.customer_id=b.id and a.company_id=? and a.loan_status in (3,6)"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("");
		if (CommonUtil.getIntValue(reqJson.getString("hidePhone"))>0)
			sb.append("select a.id loanId,REPLACE(b.phone_no, SUBSTR(b.phone_no,4,4), '****') custPhone,b.name custName,a.req_money reqMoney,a.start_time startTime,");
		else
			sb.append("select a.id loanId,b.phone_no custPhone,b.name custName,a.req_money reqMoney,a.start_time startTime,");
		sb.append(" a.end_time endTime,a.req_date reqTime,(case when a.loan_status=6 then 1 else 0 end) isBad,")
		.append(" datediff(now(),a.end_time) delayDays,ifnull(a.late_fee - a.off_latefee,0) lateFee,a.overduer_id overduerId,")
		.append(" (select u.user_name from t_sys_user u where a.overduer_id=u.id) overduerName,a.last_overdue_time lastOverdueTime,")
		.append(" (select count(1) from t_loan_overdue_log u where u.loan_id=a.id) overdueLogNum,b.id custId")
		.append(" from t_loan a, t_customer b where a.customer_id=b.id and a.company_id=? and a.loan_status in (3,6)");
		sb.append(where).append(" order by a.end_time,b.name  asc");
				
		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}
	
	/**
	 * 催收分配给指定用户
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo assignLoanOverduer(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		String loanIds = reqJson.getString("loanIds");
		Long overduerId = reqJson.getLong("overduerId");	
		
		if(companyId == null || companyId<1 || CommonUtil.isEmpty(loanIds) || overduerId == null || overduerId < 1) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		} 
		try{
			loanService.assignLoanOverdue(reqJson);	
			result.setStatus(0);
			result.setMessage("成功");
			return result;
		}catch(Exception e){
			logger.error("系统异常",e);
			result.setStatus(1);
			result.setMessage(e.getMessage());
			return result;
		}
	}
	
	/**
	 * 设为坏帐
	 * @return
	 * @throws Exception
	 */
	public ResultInfo setLoanBad(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		Long loanId = reqJson.getLong("loanId");
		String _currnetUserId = reqJson.getString("_currnetUserId");
		
		if(companyId == null || companyId<1 || loanId == null || loanId < 1) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		}
		String sql = "update t_loan set loan_status=6,bad_userid=?,bad_time=now() where id=?";
		loanService.executeUpdate(sql, new Object[]{_currnetUserId,loanId});
		result.setStatus(0);
		result.setMessage("成功");
		return result;
	}
	
	/**
	 * 获取当前用户待催收列表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getUserOverdueLoanList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		String custPhone = reqJson.getString("custPhone");
		String rqq = reqJson.getString("rqq");
		String rqz = reqJson.getString("rqz");
		int delayDays = CommonUtil.getIntValue(reqJson.getLong("delayDays"));
		int overdueSpan = CommonUtil.getIntValue(reqJson.getInteger("overdueSpan"));	
		int excludeBad = CommonUtil.getIntValue(reqJson.getLong("excludeBad"));
		String _currnetUserId = reqJson.getString("_currnetUserId");
		
		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		params.add(_currnetUserId);
		if (!CommonUtil.isEmpty(custPhone)){
			custPhone = "%"+custPhone+"%";
			where.append(" and b.phone_no like ?");
			params.add(custPhone);
		}
		if (!CommonUtil.isEmpty(rqq)){
			where.append(" and a.end_time > ?");
			params.add(rqq);
		}
		if (!CommonUtil.isEmpty(rqz)){
			rqz = rqz.substring(0,10)+" 23:59:59";
			where.append(" and a.end_time <= ?");
			params.add(rqz);
		}
		if (delayDays > 0){
			where.append(" and datediff(now(),a.end_time)>= ?");
			params.add(delayDays);
		}
		if (overdueSpan > 0){
			where.append(" and datediff(now(),a.last_overdue_time)>= ?");
			params.add(delayDays);
		}
		if (excludeBad > 0){
			where.append(" and a.loan_status=3");
		}
		
		// 取得总记录行数
		String sql = "select count(1) cnt from t_loan a, t_customer b where a.customer_id=b.id and a.company_id=? and a.overduer_id=? and a.loan_status in (3,6)"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("");
		if (CommonUtil.getIntValue(reqJson.getString("hidePhone"))>0)
			sb.append("select a.id loanId,REPLACE(b.phone_no, SUBSTR(b.phone_no,4,4), '****') custPhone,b.name custName,a.req_money reqMoney,a.start_time startTime,");
		else
			sb.append("select a.id loanId,b.phone_no custPhone,b.name custName,a.req_money reqMoney,a.start_time startTime,");
		sb.append(" a.end_time endTime,a.req_date reqTime,(case when a.loan_status=6 then 1 else 0 end) isBad,")
		.append(" datediff(now(),a.end_time) delayDays,ifnull(a.late_fee - a.off_latefee,0) lateFee,a.overduer_id overduerId,")
		.append(" (select u.user_name from t_sys_user u where a.overduer_id=u.id) overduerName,a.last_overdue_time lastOverdueTime,")
		.append(" (select count(1) from t_loan_overdue_log u where u.loan_id=a.id) overdueLogNum,a.next_overdue_time nextOverdueTime,b.id custId")
		.append(" from t_loan a, t_customer b where a.customer_id=b.id and a.company_id=? and a.overduer_id=? and a.loan_status in (3,6)");
		sb.append(where).append(" order by nextOverdueTime asc");
				
		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}
	
	/**
	 * 添加催款记录
	 * @return
	 * @throws Exception
	 */
	public ResultInfo addLoanOverdueLog(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		Long loanId = reqJson.getLong("loanId");
		String remark = reqJson.getString("remark");
		String nextOverdueTime = reqJson.getString("nextOverdueTime");
		String _currnetUserId = reqJson.getString("_currnetUserId");
		
		if(companyId == null || companyId<1 || loanId == null || loanId < 1 || CommonUtil.isEmpty(remark) || CommonUtil.isEmpty(nextOverdueTime)) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		}

		try{
			loanService.addLoanOverdueLog(loanId, remark, nextOverdueTime, _currnetUserId);
			result.setStatus(0);
			result.setMessage("成功");
			return result;
		}catch(Exception e){
			logger.error("系统异常",e);
			result.setStatus(1);
			result.setMessage(e.getMessage());
			return result;
		}
	}
	
	/**
	 * 获取滞纳金减免列表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getLatefeeReduceList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		String custPhone = reqJson.getString("custPhone");
		String rqq = reqJson.getString("rqq");
		String rqz = reqJson.getString("rqz");
		int delayDays = CommonUtil.getIntValue(reqJson.getLong("delayDays"));
		int excludeBad = CommonUtil.getIntValue(reqJson.getLong("excludeBad"));
		
		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		if (!CommonUtil.isEmpty(custPhone)){
			custPhone = "%"+custPhone+"%";
			where.append(" and b.phone_no like ?");
			params.add(custPhone);
		}
		if (!CommonUtil.isEmpty(rqq)){
			where.append(" and a.end_time > ?");
			params.add(rqq);
		}
		if (!CommonUtil.isEmpty(rqz)){
			rqz = rqz.substring(0,10)+" 23:59:59";
			where.append(" and a.end_time <= ?");
			params.add(rqz);
		}
		if (delayDays > 0){
			where.append(" and datediff(now(),a.end_time)>= ?");
			params.add(delayDays);
		}
		if (excludeBad > 0){
			where.append(" and a.loan_status=3");
		}
		
		// 取得总记录行数
		String sql = "select count(1) cnt from t_loan a, t_customer b where a.late_fee>0 and a.customer_id=b.id and a.company_id=? and a.loan_status in (3,6)"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("");
		if (CommonUtil.getIntValue(reqJson.getString("hidePhone"))>0)
			sb.append("select a.id loanId,REPLACE(b.phone_no, SUBSTR(b.phone_no,4,4), '****') custPhone,b.name custName,a.req_money reqMoney,a.start_time startTime,");
		else
			sb.append("select a.id loanId,b.phone_no custPhone,b.name custName,a.req_money reqMoney,a.start_time startTime,");
		sb.append(" a.end_time endTime,a.req_date reqTime,(case when a.loan_status=6 then 1 else 0 end) isBad,")
		.append(" datediff(now(),a.end_time) delayDays,ifnull(a.late_fee,0) lateFeeAll,ifnull(a.off_latefee,0) lateFeeReduce,ifnull(a.late_fee - a.off_latefee,0) lateFee,a.overduer_id overduerId,")
		.append(" (select u.user_name from t_sys_user u where a.overduer_id=u.id) overduerName,a.last_overdue_time lastOverdueTime,")
		.append(" (select count(1) from t_loan_overdue_log u where u.loan_id=a.id) overdueLogNum,a.next_overdue_time nextOverdueTime,b.id custId")
		.append(" from t_loan a, t_customer b where a.late_fee>0 and a.customer_id=b.id and a.company_id=? and a.loan_status in (3,6)");
		sb.append(where).append(" order by nextOverdueTime asc");
				
		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}
	
	/**
	 * 获取某货款记录的滞纳金明细列表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getLoanLatefeeList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long loanId = reqJson.getLong("loanId");
		if(loanId == null || loanId < 1) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		}
		
		// 拼接检索条件
		List<Object> params = new ArrayList<Object>();
		params.add(loanId);
		
		// 取得总记录行数
		String sql = "select count(1) cnt from t_loan_latefee a where loan_id=?";
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("select a.id latefeeId,a.type,a.money,a.create_time createTime,a.remark from t_loan_latefee a where loan_id=? order by a.id asc");
				
		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}
	
	/**
	 * 添加滞纳金减免记录
	 * @return
	 * @throws Exception
	 */
	public ResultInfo addLoanLatefeeReduceLog(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		Long loanId = reqJson.getLong("loanId");
		String remark = reqJson.getString("remark");
		int money = CommonUtil.getIntValue(reqJson.getString("money"));
		String _currnetUserId = reqJson.getString("_currnetUserId");
		
		if(companyId == null || companyId<1 || loanId == null || loanId < 1 || CommonUtil.isEmpty(remark) || money<1) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		}

		// 判断减免的滞纳金总额是否超过总的滞纳金
		String sql = "select (case when (a.late_fee - a.off_latefee) < ? then 1 else 0 end) flag from t_loan a where a.id=?";
		Map<String,Object> map = readService.findOneMapBySql(sql, new Object[]{money,loanId});
		if (map == null || map.keySet().size() < 1){
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		}
		if (CommonUtil.getDoubleValue(map.get("flag")) == 1){
			result.setStatus(1);
			result.setMessage("减免的滞纳金数额过大，请检查！");
			return result;
		}
		try{
			loanService.addLatefeeReduceLog(loanId, remark, money, _currnetUserId);
			result.setStatus(0);
			result.setMessage("成功");
			return result;
		}catch(Exception e){
			logger.error("系统异常",e);
			result.setStatus(1);
			result.setMessage(e.getMessage());
			return result;
		}
	}
}
